<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;

use app\model\Comment as CommentModel;

class Comment extends BaseController
{
    protected  CommentModel $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CommentModel();
    }

    /**
     * 显示资源列表
     *
     * @param Request $request
     *
     * @return Response
     */
    public function list(Request $request): Response
    {
        $articleId = $request->param('article_id');
        if (empty($articleId)) {
            return $this->error('参数错误');
        }
        $where  = [
            'article_id' => $articleId ,
        ];
        try {
            $query   = $this->model->where($where);
            $count   = $query->count();
            $list = $query->page($this->page , $this->pageSize)->order('id', 'DESC')->select();
            return $this->success('success' , [
                'total'    => $count ,
                'page'     => $this->page ,
                'pageSize' => $this->pageSize ,
                'list'     => $list->toArray() ,
            ]);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function create(Request $request): Response
    {
        $userId = $request->uid;
        $params = $request->param();
        try {
            $result = $this->model::create([
                'article_id' => $params['article_id'] ,
                'user_id'    => $userId ,
                'comment_id' => $params['comment_id'] ?? 0 ,
                'content'    => $params['content'] ,
                'ip'         => $request->ip(),
            ]);

            return $this->success('success', $userId);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     *
     * @return Response
     */
    public function info(Request $request): Response
    {
        return $this->success();
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function edit(Request $request): Response
    {
        return $this->success();
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     *
     * @return Response
     */
    public function delete(int $id): Response
    {
        $result = $this->model::destroy($id);
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
}
